package com.sixth.docker.service.impl;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sixth.core.entity.CareOrder;
import com.sixth.core.entity.CareOrderItem;
import com.sixth.core.vo.R;
import com.sixth.docker.mapper.CareOrderItemMapper;
import com.sixth.docker.mapper.CareOrderMapper;
import com.sixth.docker.service.CareOrderService;
import com.sixth.docker.vo.CareOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @program: sixth-hospital-parent
 * @description:
 * @author: 赵庆龙
 * @create: 2024-08-19 18:33
 **/
@Service
public class CareOrderServiceImpl implements CareOrderService {
    @Autowired
    private CareOrderMapper careOrderMapper;
    @Autowired
    private CareOrderItemMapper careOrderItemMapper;
    @Override
    public R<List<CareOrder>> selectBychId(String chId) {
        List<CareOrder> careOrders = careOrderMapper.CareOrdersByChId(chId);
        return R.ok(careOrders);
    }

    @Override
    public R<CareOrder> saveCareOrderItem(CareOrderVO careOrderVO) {
        try {
            // 从 CareOrderVO 中提取 careOrder 和 careOrderItems
            CareOrder careOrder = careOrderVO.getCareOrder();
            List<CareOrderItem> careOrderItems = careOrderVO.getCareOrderItems();

            // 1. 手动创建 LambdaQueryWrapper
            LambdaQueryWrapper<CareOrder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CareOrder::getChId, careOrder.getChId())
                    .eq(CareOrder::getCoType, careOrder.getCoType());

            CareOrder existingOrder = careOrderMapper.selectOne(queryWrapper);
            String coId;

            if (existingOrder != null) {
                coId = existingOrder.getCoId();

                for (CareOrderItem item : careOrderItems) {
                    // 创建查询条件，检查是否存在相同的 CareOrderItem
                    LambdaQueryWrapper<CareOrderItem> itemQueryWrapper = new LambdaQueryWrapper<>();
                    itemQueryWrapper.eq(CareOrderItem::getCoId, coId)
                            .eq(CareOrderItem::getItemName, item.getItemName())
                            .eq(CareOrderItem::getStatus, "0");  // 只匹配状态为0的项

                    CareOrderItem existingItem = careOrderItemMapper.selectOne(itemQueryWrapper);

                    if (existingItem != null) {
                        // 如果已存在，更新数量和金额
                        existingItem.setNum(existingItem.getNum().add(item.getNum()));
                        existingItem.setAmount(existingItem.getAmount().add(item.getAmount()));

                        careOrderItemMapper.updateById(existingItem);
                    } else {
                        // 如果不存在，插入新的记录
                        String prefix = "ITEM";
                        long timestamp = System.currentTimeMillis();
                        Random random = new Random();
                        int randomNumber = random.nextInt(1000000);
                        String itemId = prefix + timestamp + String.format("%06d", randomNumber);
                        item.setCoId(coId);
                        item.setItemId(itemId);
                        item.setStatus("0");
                        item.setCreateTime(new Date());
                        careOrderItemMapper.insert(item);
                    }
                }

                // 计算总金额
                LambdaQueryWrapper<CareOrderItem> allItemsQueryWrapper = new LambdaQueryWrapper<>();
                allItemsQueryWrapper.eq(CareOrderItem::getCoId, coId);
                List<CareOrderItem> allItems = careOrderItemMapper.selectList(allItemsQueryWrapper);
                BigDecimal totalAmount = allItems.stream()
                        .map(CareOrderItem::getAmount)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                existingOrder.setAllAmount(totalAmount);
                existingOrder.setUpdateBy(careOrder.getUpdateBy());
                existingOrder.setUpdateTime(new Date());
                careOrderMapper.updateById(existingOrder);
            } else {
                // 新的 CareOrder 插入逻辑与原来相同
                String prefix = "CO";
                long timestamp = System.currentTimeMillis();
                Random random = new Random();
                int randomNumber = random.nextInt(1000000);
                coId = prefix + timestamp + String.format("%06d", randomNumber);
                careOrder.setCoId(coId);
                careOrder.setCreateBy(careOrder.getCreateBy());
                careOrder.setUpdateBy(careOrder.getUpdateBy());
                careOrder.setCreateTime(new Date());
                careOrder.setUpdateTime(new Date());
                careOrderMapper.insert(careOrder);

                for (CareOrderItem item : careOrderItems) {
                    String itemPrefix = "ITEM";
                    long itemTimestamp = System.currentTimeMillis();
                    int itemRandomNumber = random.nextInt(1000000);
                    String itemId = itemPrefix + itemTimestamp + String.format("%06d", itemRandomNumber);
                    item.setCoId(coId);
                    item.setItemId(itemId);
                    item.setStatus("0");
                    item.setCreateTime(new Date());
                    careOrderItemMapper.insert(item);
                }

                // 计算总金额
                BigDecimal totalAmount = careOrderItems.stream()
                        .map(CareOrderItem::getAmount)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                careOrder.setAllAmount(totalAmount);
                careOrderMapper.updateById(careOrder);
            }

            return R.ok(careOrder);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("保存失败: " + e.getMessage());
        }
    }

    @Override
    public R<List<CareOrder>> selectByPatientId(String patientId) {
        List<CareOrder> careOrders = careOrderMapper.selectByPatientId(patientId);
        return R.ok(careOrders);
    }

    @Override
    public R<CareOrder> deleteById(String coId) {
        careOrderMapper.deleteById(coId);
        return R.ok();
    }


}
